package com.haohan.cloud.scm.goods.core.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.haohan.cloud.scm.api.constant.ScmCommonConstant;
import com.haohan.cloud.scm.api.constant.enums.opc.YesNoEnum;
import com.haohan.cloud.scm.api.goods.entity.Goods;
import com.haohan.cloud.scm.api.goods.entity.GoodsCategory;
import com.haohan.cloud.scm.api.goods.vo.GoodsCategoryVO;
import com.haohan.cloud.scm.api.manage.entity.Merchant;
import com.haohan.cloud.scm.api.manage.entity.Shop;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.goods.core.GoodsCategoryCoreService;
import com.haohan.cloud.scm.goods.service.GoodsCategoryService;
import com.haohan.cloud.scm.goods.service.GoodsService;
import com.haohan.cloud.scm.goods.utils.ScmGoodsUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Set;

/**
 * @author dy
 * @date 2020/4/7
 */
@Service
@AllArgsConstructor
public class GoodsCategoryCoreServiceImpl implements GoodsCategoryCoreService {

    private final GoodsService goodsService;
    private final GoodsCategoryService goodsCategoryService;
    private final ScmGoodsUtils scmGoodsUtils;


    @Override
    public GoodsCategoryVO fetchInfo(String categoryId) {
        GoodsCategory category = goodsCategoryService.getById(categoryId);
        if (null == category) {
            throw new ErrorDataException("商品分类有误");
        }
        return new GoodsCategoryVO(category);
    }

    /**
     * 新增
     *
     * @param category
     * @return
     */
    @Override
    public boolean addCategory(GoodsCategory category) {
        // 店铺
        checkShop(category);
        // 重名验证
        checkName(category.getName(), null, category.getShopId());
        if (null == category.getCategoryType()) {
            category.setCategoryType(YesNoEnum.yes);
        }
        if (null == category.getStatus()) {
            category.setStatus(YesNoEnum.yes);
        }
        return goodsCategoryService.saveCategory(category);
    }

    /**
     * 修改
     *
     * @param category
     * @return
     */
    @Override
    public boolean modifyCategory(GoodsCategory category) {
        GoodsCategory exist = goodsCategoryService.getById(category.getId());
        if (null == exist) {
            throw new ErrorDataException("商品分类有误");
        }
        checkShop(category);
        checkName(category.getName(), category.getId(), category.getShopId());
        return goodsCategoryService.updateCategoryById(category);
    }


    /**
     * 重名验证  同一店铺下分类名称不重复
     *
     * @param name
     * @param id   排除的id
     */
    private void checkName(String name, String id, String shopId) {
        List<GoodsCategory> list = goodsCategoryService.list(Wrappers.<GoodsCategory>query().lambda()
                .eq(GoodsCategory::getName, name)
                .eq(GoodsCategory::getShopId, shopId)
                .ne(null != id, GoodsCategory::getId, id)
        );
        if (!list.isEmpty()) {
            throw new ErrorDataException("已存在相同名称的分类");
        }
    }


    /**
     * 设置商家id
     *
     * @param category
     */
    private void checkShop(GoodsCategory category) {
        Shop shop = scmGoodsUtils.fetchShopById(category.getShopId());
        if (null == shop) {
            throw new ErrorDataException("店铺有误");
        }
        category.setMerchantId(shop.getMerchantId());
    }

    /**
     * 删除分类及子分类
     *
     * @param categoryId
     * @return
     */
    @Override
    public boolean deleteById(String categoryId) {
        GoodsCategory exist = goodsCategoryService.getById(categoryId);
        if (null == exist) {
            throw new ErrorDataException("商品分类有误");
        }
        // 分类及子分类下商品数量
        int num = countGoods(categoryId);
        if (num > 0) {
            throw new ErrorDataException("分类及子分类下存在商品不可删除");
        }
        return goodsCategoryService.removeCategoryById(categoryId);
    }

    /**
     * 分类及子分类下商品数量
     *
     * @param id
     */
    private int countGoods(String id) {
        // 查询子分类
        Set<String> idList = goodsCategoryService.fetchChildren(id);
        return goodsService.count(Wrappers.<Goods>query().lambda()
                .in(Goods::getGoodsCategoryId, idList)
        );
    }

    /**
     * 获取店铺的默认导入分类(没有时创建)
     *
     * @param shop
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public GoodsCategory fetchDefaultCategory(Shop shop) {
        String shopId = shop.getId();
        String merchantId = shop.getMerchantId();
        GoodsCategory parent = goodsCategoryService.fetchByName(shopId, ScmCommonConstant.DEFAULT_PARENT_NAME);
        if (null == parent) {
            parent = new GoodsCategory();
            parent.setShopId(shopId);
            parent.setName(ScmCommonConstant.DEFAULT_PARENT_NAME);
            parent.setSort(BigDecimal.TEN);
            // 不展示
            parent.setCategoryType(YesNoEnum.no);
            parent.setMerchantId(merchantId);
            goodsCategoryService.saveCategory(parent);
        }
        GoodsCategory category = goodsCategoryService.fetchByName(shopId, ScmCommonConstant.DEFAULT_CATEGORY_NAME);
        if (null == category) {
            category = new GoodsCategory();
            category.setShopId(shopId);
            category.setName(ScmCommonConstant.DEFAULT_CATEGORY_NAME);
            category.setSort(BigDecimal.TEN);
            // 不展示
            category.setCategoryType(YesNoEnum.no);
            category.setMerchantId(merchantId);
            category.setParentId(parent.getId());
            goodsCategoryService.saveCategory(category);

        }
        return category;
    }

    @Override
    public GoodsCategoryVO fetchPlatformCategory(String categoryId) {
        GoodsCategory category = goodsCategoryService.getById(categoryId);
        if (null == category) {
            throw new ErrorDataException("商品分类有误");
        }
        Merchant pm = scmGoodsUtils.fetchPlatformMerchant();
        if (StrUtil.equals(category.getMerchantId(), pm.getId())) {
            throw new ErrorDataException("所选分类不能为平台商家店铺的商品分类");
        }
        String platformCategoryId = null;
        try {
            JSONObject json = JSONUtil.parseObj(category.getRemarks());
            Object obj = json.get("categoryId");
            if (null != obj) {
                platformCategoryId = obj.toString();
            }
        } catch (Exception ignored) {
        }
        if (StrUtil.isNotEmpty(platformCategoryId)) {
            category = goodsCategoryService.getById(platformCategoryId);
            if (null != category) {
                return new GoodsCategoryVO(category);
            }
        }
        // 商品分类无对应平台商品分类
        return null;
    }

    /**
     * 查询分类及所有父级
     *
     * @param categoryId
     * @param shopId     验证分类的shopId
     * @return
     */
    @Override
    public List<GoodsCategory> findAllParentWithSelfById(String categoryId, String shopId) {
        GoodsCategory category = goodsCategoryService.getById(categoryId);
        if (null == category || !StrUtil.equals(category.getShopId(), shopId)) {
            throw new ErrorDataException("分类有误");
        }
        return goodsCategoryService.fetchAllParentWithSelf(categoryId);
    }
}
